import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin,message } from 'antd';
import React from 'react';
import { history, connect } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import EditPwd from './EditPwd';
import {updatePwdByOldPwd} from '@/services/user';

class AvatarDropdown extends React.Component {
  onMenuClick = (event) => {
    const { key } = event;

    if (key === 'logout') {
      const { dispatch } = this.props;
      if (dispatch) {
        dispatch({
          type: 'user/logout',
        });
      }
      history.replace('/user/login/', '/');
      return;
    }else if(key === 'center'){
      history.push(`/info/details`);
    }else if(key === 'settings'){
      this.setState({visible : true});
    }
  };

  constructor() {
    super();
    this.state = {
      visible: false,
      loading: false
    };
  }

  handleCancel = () => {
    this.setState({visible : false});
  };

  handleSubmit = (values) => {
    this.setState({loading : true});
    updatePwdByOldPwd(values).then(res =>{
      if (res.flag){
        message.success('二级密码修改成功！');
        this.setState({visible : false});
      }else {
        message.error(res.error);
      }
    });
    this.setState({loading : false});
  };

  render() {
    const {
      currentUser = {
        avatar: '',
        name: '',
      },
      menu,
    } = this.props;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        <Menu.Item key="center">
          <UserOutlined />
          个人中心
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="settings">
          <SettingOutlined />
          修改二级密码
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <LogoutOutlined />
          退出登录
        </Menu.Item>
      </Menu>
    );
    return currentUser && currentUser.name ? (<>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" />
          <span className={styles.name}>{currentUser.name}</span>
        </span>
      </HeaderDropdown>
        <EditPwd
          visible={this.state.visible}
          loading={this.state.loading}
          onCancel={this.handleCancel}
          onSubmit={this.handleSubmit}
        />
      </>
    ) : (
      <span className={`${styles.action} ${styles.account}`}>
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      </span>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
